package com.mine.frame.mylandemo.ui.forick

import android.annotation.SuppressLint
import android.app.Service
import android.content.ComponentName
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.text.Editable
import android.util.Log
import com.blankj.utilcode.util.*
import com.mine.frame.common.base.BaseActivity
import com.mine.frame.mylandemo.R
import com.mine.frame.mylandemo.adapter.forick.Panel3In1Adapter
import com.mine.frame.mylandemo.entity.forick.ControlBean
import com.mine.frame.mylandemo.mvp.iview.IPanel3In1
import com.mine.frame.mylandemo.mvp.presenter.Panel3In1Presenter
import com.mine.frame.mylandemo.service.MineConnectService
import com.mine.frame.mylandemo.service.SocketState
import com.swallowsonny.convertextlibrary.toHexString
import com.third.device.mg.serialport.MGSerialPort
import com.third.device.mg.serialport.utils.to2ByteL
import kotlinx.android.synthetic.main.atv_connect.*
import kotlinx.android.synthetic.main.atv_forick_panel_3in1.*
import kotlinx.android.synthetic.main.layout_connect.*
import kotlinx.android.synthetic.main.layout_connect.btnConnect
import kotlinx.android.synthetic.main.layout_connect.btnDisconnect
import kotlinx.android.synthetic.main.layout_connect.edtIP
import kotlinx.android.synthetic.main.layout_connect.edtPort
import kotlinx.android.synthetic.main.layout_connect.tvInfo
import kotlinx.android.synthetic.main.layout_connect.viewIndicator

/**
 * company 广东玛格家居有限公司
 * @author smoker
 * @Date 2021/12/27
 * Description:佛雷克三合一环境面板
 */
@SuppressLint("SetTextI18n")
class Panel3In1Atv : BaseActivity<IPanel3In1, Panel3In1Presenter>(), IPanel3In1 {
    /*当前连接的IP地址 和 端口号*/
    private var ipStr = ""
    private var port = 61233
    private var mService: MineConnectService? = null
    /*设备地址*/
    private val devAddress = 1
    private var readHLR :ByteArray? = null

    private val mAdapter by lazy { Panel3In1Adapter() }

    private val serviceConnect: ServiceConnection by lazy {
        object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                SnackbarUtils.with(tvInfo).setMessage("正在连接服务器...").showSuccess()
                service?.let {
                    if (it is MineConnectService.MineConnectServiceBinder) {
                        mService = it.getService()
                        tvInfo.text = "获取到Android.Service控制对象"
                        initSocket()
                    }
                }
            }

            override fun onServiceDisconnected(name: ComponentName?) {
                mService = null
            }
        }
    }

    override fun initLayoutId(): Int = R.layout.atv_forick_panel_3in1

    override fun initPresenter(): Panel3In1Presenter = Panel3In1Presenter(this)

    override fun initLayoutAfter(savedInstanceState: Bundle?) {
        ipStr = intent?.getStringExtra("sel-ip").toString()
        edtIP.text = Editable.Factory.getInstance().newEditable(ipStr)
        connectAndDisconnect()
        initRecycler()
        mPresenter.createControlData()
    }

    /**
     * 连接和取消连接
     */
    private fun connectAndDisconnect() {
        ClickUtils.applySingleDebouncing(arrayOf(btnConnect ,btnDisconnect)){
            when(it.id){
                R.id.btnConnect ->{
                    KeyboardUtils.hideSoftInput(this)
                    if (edtIP.text.isNullOrEmpty()){
                        SnackbarUtils.with(edtIP).setMessage("请输入IP地址").showWarning()
                        return@applySingleDebouncing
                    }else{
                        ipStr = edtIP.text.toString()
                    }


                    if (edtPort.text.isNullOrEmpty()){
                        SnackbarUtils.with(edtIP).setMessage("请输入端口号").showWarning()
                        return@applySingleDebouncing
                    }else{
                        port =edtPort.text.toString().toInt()
                        if (port < 1 || port > 65535){
                            SnackbarUtils.with(edtIP).setMessage("端口号异常(1,65535)").showWarning()
                            return@applySingleDebouncing
                        }
                    }
                    if (ipStr.isEmpty()){
                        SnackbarUtils.with(edtIP).setMessage("IP地址异常").showError()
                        return@applySingleDebouncing
                    }

                    onBindMineService()
                }
                R.id.btnDisconnect ->{
                    mService?.disconnect()
                }
            }
        }

    }

    /**
     * 绑定service
     */
    private fun onBindMineService() {
        mService?.let {
            tvInfo.text = "已Bind Android.Service"
            initSocket()
        }?:let {
            ServiceUtils.bindService(MineConnectService::class.java, serviceConnect, Service.BIND_AUTO_CREATE)
        }
    }

    /**
     * 创建Socket连接
     */
    private fun initSocket(){
        mService?.connect(ipStr ,port)
        mService?.addConnectStateListener {
            when(it){
                SocketState.SocketDisConnect ->{
                    tvInfo.text = "系统:Socket暂未连接"
                    updateIndicator(false)
                }
                SocketState.SocketConnecting ->{
                    tvInfo.text = "系统:Socket正在连接中..."
                }
                SocketState.SocketConnectSuccess ->{
                    tvInfo.text = "系统:Socket已连接"
                    updateIndicator(true)
                }
                SocketState.SocketAddressInvalid ->{
                    tvInfo.text = "系统:地址无效，请检查端口是否正确"
                }
                SocketState.SocketOutputStreamOpen ->{
                    tvInfo.text = "系统:Socket 开启OutputStream通道"
                }// Socket 开启OutputStream通道
                SocketState.SocketOutputStreamClose ->{
                    tvInfo.text = "系统:Socket 关闭OutputStream通道"
                }// Socket 关闭OutputStream通道
                SocketState.SocketInputStreamOpen ->{
                    tvInfo.text = "系统:Socket 开启InputStream通道"
                }// Socket 开启InputStream通道
                SocketState.SocketInputStreamClose ->{
                    tvInfo.text = "系统:Socket 关闭InputStream通道"
                }// Socket 关闭InputStream通道
                SocketState.SocketWriting ->{
                    tvInfo.text = "系统:Socket 发送中"
                }//Socket 发送中
                SocketState.SocketWriteError ->{
                    tvInfo.text = "系统:Socket 发送失败"
                }// Socket 发送失败
                SocketState.SocketWriteSuccess ->{
                    tvInfo.text = "系统:Socket 发送成功"
                    showSuccess("发送成功")
                }// Socket 发送成功
                SocketState.SocketReading ->{
                    tvInfo.text = "系统:Socket 读取中"
                }// Socket 读取中
                SocketState.SocketReadError ->{
                    tvInfo.text = "系统:Socket 读取失败"
                }// Socket 读取失败
                SocketState.SocketReadSuccess->{
                    tvInfo.text = "系统:Socket 读取成功"
                }// Socket 读取成功

            }
            Log.e("Panel3In1Atv -->" ,tvInfo.text.toString())
        }
        mService?.addReadInfoListener {
            LogUtils.d("服务器返回的数据:${it.toHexString(true)}")
            tvInfo.text = "接收:${it.toHexString(true)}"
            mPresenter.analysisReadMsg(it)
        }
    }

    /**
     * 更新指示器
     */
    private fun updateIndicator(connect:Boolean){
        val resId = if (connect){
            R.drawable.blue_circle
        }else{
            R.drawable.red_circle
        }
        viewIndicator.setBackgroundResource(resId)
    }


    override fun onDestroy() {
        super.onDestroy()
        mService?.let {
            ServiceUtils.unbindService(serviceConnect)
        }
    }

    private fun initRecycler(){
        mRecycler.adapter = mAdapter
        mAdapter.setOnItemClickListener{ _, _, position ->
            val controlBean = mAdapter.data[position]
            if (!controlBean.isHeader){
                controlBean.command?.let {
                    mService?.sent(it)?:let {
                        SnackbarUtils.with(btnConnect).setMessage("未连接设备").showError(true)
                    }
                }?:let {
                    SnackbarUtils.with(btnConnect).setMessage("暂不支持设置指令").showWarning(true)
                }
            }
        }
        mAdapter.addChildClickViewIds(R.id.btnGet)
        mAdapter.setOnItemChildClickListener{_, _, position ->
            val controlBean = mAdapter.data[position]
            controlBean.readHLR?.let {
                this.readHLR = it
                val command = MGSerialPort.instance.getForick().panel3In1().getReadHLRCommand(getAddress(),it)
                mService?.sent(command) ?:let {
                    SnackbarUtils.with(btnConnect).setMessage("未连接设备").showError(true)
                }
                showReadMsg("--")
            }
        }
    }

    override fun getAddress(): Byte = devAddress.to2ByteL()[0]

    override fun initControlList(data: MutableList<ControlBean>) {
        mAdapter.setList(data)
    }

    override fun getReadHLRAddress(): ByteArray? = readHLR
    override fun showReadMsg(string: String) {
        tvRead.text = string
    }

}